<?php

declare(strict_types=1);

namespace App\Controller;

use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Contract\RequestInterface;
use App\Controller\BaseController;
use App\Model\Chat as ChatModel;
use App\Model\User as UserModel;
use Hyperf\Amqp\Producer;
use App\Amqp\Producer\DemoProducer;
use Hyperf\Context\ApplicationContext;

#[AutoController]
class ChatController extends BaseController
{
    private $request;

    /**
     * 对话增加
     */
    public function chat_add(RequestInterface $request)
    {
        $isAuth = $this->Auth($request, 1);
        $AuthInfo = json_decode($isAuth, true);
        if ($AuthInfo['err'] === 0) {
            $data = $request->post();
            $jsonData = json_decode($data['data'], true);
            $nickName = filter_var($jsonData['content'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
            $avatarUrl = filter_var($jsonData['userid'], FILTER_SANITIZE_NUMBER_INT);
            $userid = filter_var($jsonData['friendid'], FILTER_SANITIZE_NUMBER_INT);
            if ($nickName === false || $avatarUrl === false || $userid === false) {
                $res['err'] = 1;
                $res['msg'] = "对话增加失败，参数错误";
            } else {
                $result = ChatModel::chat_add($data['data']);
                if ($result) {
                    $res['err'] = 0;
                    $res['msg'] = "对话增加成功";
                } else {
                    $res['err'] = 1;
                    $res['msg'] = "对话增加失败，加入失败";
                }
            }
        } else {
            $res['err'] = 2;
            $res['msg'] = 'toekn认证失败，重新登录';
        }
        return json_encode($res);
    }

    /**
     * 获取对话记录
     */
    public function chat_get(RequestInterface $request)
    {
        $isAuth = $this->Auth($request, 1);
        $AuthInfo = json_decode($isAuth, true);
        $userId = intval($request->post('userId'));
        $friendId = intval($request->post('friendId'));
        if ($AuthInfo['err'] === 0 && $userId > 0 && $friendId > 0) {
            $list = json_encode(ChatModel::getList($AuthInfo['token'], $friendId, $userId));
            $res['err'] = 0;
            $res['msg'] = 'toekn认证成功';
            $res['friendInfo'] = UserModel::friendDetail($friendId);
            $res['chatList'] = $list;
        } else {
            $res['err'] = 1;
            $res['msg'] = 'toekn认证失败，重新登录';
            $res['friendInfo'] = '';
            $res['chatList'] = '';
        }
        return json_encode($res);
    }
}
